/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.mailTemplate;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.common.util.RegExUtil;
import com.blandware.atleap.model.core.MailTemplate;
import com.blandware.atleap.service.core.MailTemplateManager;
import com.blandware.atleap.service.exception.MailAddressException;
import com.blandware.atleap.service.util.MailEngine;
import com.blandware.atleap.webapp.action.core.BaseAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.RequestUtils;
import org.apache.velocity.exception.VelocityException;
import org.apache.oro.text.regex.MalformedPatternException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.HashMap;

/**
 * <p>Prepares message to preview on JSP page
 * </p>
 * <p><a href="PreviewMessageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.12 $ $Date: 2006/08/03 10:07:58 $
 * @struts.action path="/core/mailTemplate/previewMessage"
 * scope="request"
 * validate="false"
 * roles="core-mailTemplate-previewMessage"
 * @struts.action-forward name="previewMessage"
 * path=".core.mailTemplate.previewMessage"
 */
public final class PreviewMessageAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map model = (Map) request.getAttribute("model");
		if ( model == null ) {
			model = new HashMap();
		}
		MailEngine mailEngine = (MailEngine) getBean(Constants.MAIL_ENGINE_BEAN);

		String templateIdentifier = (String) request.getAttribute("identifier");

		MailTemplateManager mailTemplateManager = (MailTemplateManager) getBean(Constants.MAIL_TEMPLATE_MANAGER_BEAN);
		MailTemplate template = mailTemplateManager.findMailTemplateByIdentifier(templateIdentifier);

		if ( template == null ) {
			// mail template not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("mailTemplateNotFound", new ActionMessage("core.mailTemplate.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listMailTemplates");
		}

		String locale = (String) request.getAttribute("locale");
		if ( locale == null ) {
			locale = (RequestUtils.getUserLocale(request, null)).getLanguage();
		}

		String from = null;
		try {
			from = mailEngine.mergeTemplate(templateIdentifier, "from", locale, model, false);
			// validate address
			mailEngine.prepareAddress(from, (String) template.getCharset().get(locale));
			from = StringUtil.htmlEncode(from);
		} catch ( VelocityException e ) {
			from = e.getLocalizedMessage();
		} catch ( MailAddressException e ) {
			from = e.getLocalizedMessage();
		}

		String subject = null;
		try {
			subject = mailEngine.mergeTemplate(templateIdentifier, "subject", locale, model, false);
			subject = StringUtil.htmlEncode(subject);
		} catch ( VelocityException e ) {
			subject = e.getLocalizedMessage();
		}

		String body = null;
		try {
			body = mailEngine.mergeTemplate(templateIdentifier, "body", locale, model, !template.isPlain());
			if ( template.isPlain() ) {
				body = StringUtil.htmlEncode(body);
			}

			// replace encoded line breaks (&lt;br /&gt;) with normal tags (<br />);

			try {
				body = RegExUtil.replaceAll(body, "&lt;br\040*/?&gt;", "<br />");
			} catch ( MalformedPatternException e ) {
				// ignore
			}

		} catch ( VelocityException e ) {
			body = e.getLocalizedMessage();
		}

		request.setAttribute("from", from);
		request.setAttribute("subject", subject);
		request.setAttribute("body", body);
		if ( template.isPlain() ) {
			request.setAttribute("templateIsPlain", "true");
		}

		return mapping.findForward("previewMessage");
	}
}